﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Companies.WebParts.IOHeader
{
    public partial class IOHeaderUserControl : UserControl
    {
        private readonly string _defaultPageUrl;

        public IOHeaderUserControl()
        {
            var siteId = SPContext.Current.Site.ID;
            var webId = SPContext.Current.Web.ID;

            using(var site = new SPSite(siteId))
            using (var web = site.OpenWeb(webId))
            {
                SPSecurity.CatchAccessDeniedException = false;

                try
                {
                    var pubWeb = PublishingWeb.GetPublishingWeb(web);
                    _defaultPageUrl = pubWeb.DefaultPage.ServerRelativeUrl;
                }
                catch (Exception ex)
                {
                    Logger.LogWarning("IOHeaderUserControl.ctor: exception occured");
                    Logger.LogException(ex);
                }
            }
        }
            

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            productsDropDown.SelectedIndexChanged += ProductsDropDownSelectedIndexChanged;
            productsRepeater.ItemDataBound += ProductsRepeaterItemDataBound;
            productLevel1.SelectedIndexChanged += ProductLevel1SelectedIndexChanged;            
        }

        void ProductLevel1SelectedIndexChanged(object sender, EventArgs e)
        {
            var id = productLevel1.SelectedValue;
            Response.Redirect(_defaultPageUrl + "?l3=" + id + "&p=" + Request.QueryString["p"]);
            Response.End();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (IsPostBack)
                return;

            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);

            try
            {
                var products = repository.GetAllProductsResults();
                if (products != null)
                    if (products.Count > 0)
                        products = products.OrderBy(prd => prd.Title).ToList();

                productsDropDown.DataSource = products;
                productsDropDown.DataBind();

                var item = new ListItem(Resources.GetResourceString("SelectProductDropDownLabel"), string.Empty);
                productsDropDown.Items.Insert(0, item);

                var productId = Request.QueryString["p"] ?? string.Empty;
                if (productsDropDown.Items.FindByValue(productId) != null)
                    productsDropDown.SelectedValue = productId;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            noLevelBlock.Visible = false;
            level1Block.Visible = false;
            level2Block.Visible = false;
            productBlock.Visible = false;

            var l1 = repository.GetActiveLevel1();
            var l3 = repository.GetActiveLevel3();
            var p = repository.GetActiveProduct();

            if (l3 != null)
            {
                level2TitleLink.InnerText = l3.Title;
                level2TitleLink.HRef = _defaultPageUrl + "?l3=" + l3.Id;
                productsRepeater.DataSource = repository.GetProductResults();
                productsRepeater.DataBind();
                level2Block.Visible = true;
            }
            else if (l1 != null)
            {
                level1TitleLink.InnerText = l1.Title;
                level1TitleLink.HRef = _defaultPageUrl + "?l1=" + l1.Id;
                level1Block.Visible = true;
            }              
            else if(p != null)
            {
                productTitleLink.InnerText = p.Title;
                productTitleLink.HRef = _defaultPageUrl + "?p=" + p.Id;
                productBlock.Visible = true;

                productLevel1.DataSource = repository.GetLevel3ForProduct(p);
                productLevel1.DataBind();
                productLevel1.Items.Insert(0, new ListItem(Resources.GetResourceString("SelectClassificationDropDownLabel"), string.Empty));

            }
            else if(SPContext.Current.ListItem != null)
                if(SPContext.Current.ListItem.File.Name.ToLower()=="default.aspx")
                    noLevelBlock.Visible = true;
        }

        protected void ProductsDropDownSelectedIndexChanged(object sender, EventArgs e)
        {
            var pId = productsDropDown.SelectedValue;
            var query = string.Empty;
            
            if (!string.IsNullOrEmpty(pId))
                query += "&p=" + pId;

            if (query.Length > 0)
                query = query.Substring(1);

            Response.Redirect(_defaultPageUrl + "?" + query);
        }

        protected void ProductsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var product = (IoProduct)e.Item.DataItem;

            var link = (HtmlAnchor)e.Item.FindControl("productLink");
            link.HRef = product.Url;
            link.InnerText = product.Title;
            link.ID += "_" + e.Item.ItemIndex;
        }
    }
}
